package com.bdqn.tour.servlet.Hzy;

import com.alibaba.fastjson.JSON;
import com.bdqn.tour.pojo.User;
import com.bdqn.tour.service.HzyInfoVerifyService;
import com.bdqn.tour.service.impl.HzyInfoVerifyServiceImpl;
import com.bdqn.tour.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/validatePassword")
public class ValidatePasswordServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");

        String phone = req.getParameter("phone");
        String password = req.getParameter("password");

        Map<String, Object> result = new HashMap<>();

        if (phone == null || phone.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "手机号或密码不能为空");
            resp.getWriter().write(JSON.toJSONString(result));
            return;
        }

        // 对密码进行MD5加密(5次)
        String encryptedPassword = MD5Util.md5(password, 5);

        HzyInfoVerifyService infoVerifyService = new HzyInfoVerifyServiceImpl();
        User user = infoVerifyService.validatePassword(phone, encryptedPassword);

        if (user != null) {
            result.put("success", true);
            result.put("message", "验证成功");
        } else {
            result.put("success", false);
            result.put("message", "密码错误");
        }

        resp.getWriter().write(JSON.toJSONString(result));
    }
}
